package com.taylor.community.controller;

import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.taylor.community.annotation.LoginRequired;
import com.taylor.community.entity.Comment;
import com.taylor.community.entity.DiscussPost;
import com.taylor.community.entity.Page;
import com.taylor.community.entity.User;
import com.taylor.community.service.*;
import com.taylor.community.util.CommunityConstant;
import com.taylor.community.util.CommunityUtil;
import com.taylor.community.util.HostHolder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController implements CommunityConstant {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private UserService userService;
    @Value("${community.path.upload}")
    private String uploadPath;
    @Value("${community.path.domain}")
    private String domain;
    @Value("${server.servlet.context-path}")
    private String contextPath;
    @Autowired
    private HostHolder hostHolder;
    @Autowired
    private LikeService likeService;
    @Autowired
    private FollowService followService;
    @Autowired
    private DiscussPostService discussPostService;
    @Autowired
    private CommentService commentService;
    @Value("${qiniu.bucket.header.name}")
    private String headerBucketName;
    @Value("${qiniu.bucket.header.url}")
    private String headerBucketUrl;
    @Value("${qiniu.key.access}")
    private String accessKey;
    @Value("${qiniu.key.secret}")
    private String secretKey;
    @LoginRequired
    //个人设置资源路径
    @RequestMapping(path = "/setting", method = RequestMethod.GET)
    public String getSettingPage(Model model) {
        //上传文件名称（随机生成）
        //云服务器有缓存 如果是同名文件 上传之后不会立刻访问服务器的 而是先访问到缓存 即不会立刻刷新
        //另外 随机名称 可以被保留历史上传 方便以后做业务扩展（硬盘便宜，不用过于担心成本）
        String fileName = CommunityUtil.generateUUID();
        //生成响应信息
        StringMap policy = new StringMap();
        policy.put("returnBody",CommunityUtil.getJSONString(200));
        //生成上传凭证
        Auth auth = Auth.create(accessKey,secretKey);
        String uploadToken = auth.uploadToken(headerBucketName,fileName,3600,policy);
        model.addAttribute("uploadToken",uploadToken);
        model.addAttribute("fileName",fileName);
        return "/site/setting";
    }
    @RequestMapping(path = "/header/url",method = RequestMethod.POST)
    @ResponseBody
    public String updateHeaderUrl(String fileName){
        if(StringUtils.isBlank(fileName)){
            return CommunityUtil.getJSONString(1,"文件名不能为空！");
        }
        String url = headerBucketUrl + "/"
                + fileName;
        userService.updateHeader(hostHolder.getUser().getId(),url);
        return CommunityUtil.getJSONString(200,"上传头像成功！");
    }
    //头像文件上传到七牛云 故以下方法不再使用
    /**
     * 上传用户头像
     *
     * @param headImage
     * @param model
     * @return
     */
    @LoginRequired
    @RequestMapping(path = "/upload", method = RequestMethod.POST)
    public String uploadHeader(MultipartFile headImage, Model model) {
        if (headImage == null) {
            model.addAttribute("error", "您还没有选择图片");
            return "/site/setting";
        }
        String fileName = headImage.getOriginalFilename();//获取文件名
        String suffix = fileName.substring(fileName.lastIndexOf("."));//获取文件名的后缀名
        if (StringUtils.isBlank(suffix)) {
            model.addAttribute("error", "文件格式不正确");
            return "/site/setting";
        }
        //生成随机的文件名
        fileName = CommunityUtil.generateUUID() + suffix;
        //确定文件的存放路径：预设的路径 + 文件名
        File dest = new File(uploadPath + "/" + fileName);
        try {
            //将图片写入到目标文件
            headImage.transferTo(dest);
        } catch (Exception e) {
            logger.error("上传文件失败：" + e.getMessage());
            throw new RuntimeException("上传文件失败，服务器发送异常！", e);
        }
        //更新当前用户头像的web访问路径
        User user = hostHolder.getUser();
        String headerUrl = domain + contextPath + "/user/header/" + fileName;
        userService.updateHeader(user.getId(), headerUrl);
        return "redirect:/index";
    }
    //头像文件上传到七牛云 故以下方法不再使用
    /**
     * 读取头像 因为前端是通过loginUser.headerUrl来获取登录用户在数据库的字段header_url的值
     * 而拿到这个值的时候相当与访问了该值（头像路径）
     *
     * @param fileName
     * @param response
     */
    @RequestMapping(path = "/header/{fileName}", method = RequestMethod.GET)
    public void getHeader(@PathVariable("fileName") String fileName, HttpServletResponse response) {
        //头像在服务器存放的路径
        fileName = uploadPath + "/" + fileName;
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        response.setContentType("image/" + suffix);
        try (
                //这样写输入输出流会自动关闭
                OutputStream os = response.getOutputStream();
                //读取文件
                FileInputStream file = new FileInputStream(fileName);
        ) {
            byte[] buffer = new byte[1024];
            int b = 0;
            while ((b = file.read(buffer)) != -1) {
                os.write(buffer, 0, b);
            }
        } catch (IOException e) {
            logger.error("读取头像失败：" + e.getMessage());
        }
    }
    //个人主页 可以通过头像访问主页 包括其他人的主页
    @RequestMapping(path = "/profile/{userId}",method = RequestMethod.GET)
  public String getProfilePage(@PathVariable("userId") int userId,Model model) {
        User user = userService.findUserById(userId);
        if(user == null){
            throw new RuntimeException("该用户不存在！");
        }
        model.addAttribute("user",user);
        //该用户获得的点赞数量
        int likeCount = likeService.findUserLikeCount(userId);
        model.addAttribute("likeCount",likeCount);
        //该用户关注的用户数量
        long followeeCount = followService.findFolloweeCount(userId,ENTITY_TYPE_USER);
        model.addAttribute("followeeCount",followeeCount);
        //该用户粉丝数量
        long followerCount = followService.findFollowerCount(ENTITY_TYPE_USER,userId);
        model.addAttribute("followerCount",followerCount);
        //是否已经关注 未登录肯定是未关注
        boolean hasFollowed = false;
        if(hostHolder.getUser() != null){
            //userId是当前主页用户的id
            hasFollowed = followService.hasFollowed(hostHolder.getUser().getId(),ENTITY_TYPE_USER,userId);
        }
        model.addAttribute("hasFollowed",hasFollowed);
        return "/site/profile";
    }

    /**
     * 查看某用户发布的帖子列表
     * @param userId
     * @param page
     * @param model
     * @return
     */
    @RequestMapping(path = "/mypost/{userId}",method = RequestMethod.GET)
    public String getMypost(@PathVariable("userId")int userId, Page page, Model model){
        User user = userService.findUserById(userId);
        if(user == null){
            throw new RuntimeException("该用户不存在！");
        }
        model.addAttribute("user",user);
        page.setRows(discussPostService.findDiscussPostRows(userId));
        page.setPath("/user/mypost/"+userId);
        //帖子列表
        List<DiscussPost> discussPostList = discussPostService.findDiscussPosts(userId,page.getOffset(),page.getLimit(),0);
        List<Map<String,Object>> discussVoList = new ArrayList<>();
        if(discussPostList != null){
            for(DiscussPost post : discussPostList){
                Map<String,Object> map = new HashMap<>();
                map.put("discussPost",post);
                map.put("likeCount",likeService.findEntityLikeCount(ENTITY_TYPE_POST,post.getId()));
                discussVoList.add(map);
            }
        }
        model.addAttribute("discussPosts",discussVoList);
        return "/site/my-post";
    }

    /**
     * 某用户对帖子的回复列表
     * @param userId
     * @param page
     * @param model
     * @return
     */
    @RequestMapping(path = "/myreply/{userId}",method = RequestMethod.GET)
    public String getMyReply(@PathVariable("userId")int userId,Page page,Model model){
        User user = userService.findUserById(userId);
        if(user == null){
            throw new RuntimeException("该用户不存在！");
        }
        model.addAttribute("user",user);
        //分页信息
        page.setPath("/user/myreply/"+userId);
        page.setRows(commentService.findUserCount(userId));
        //回复列表
        List<Comment> commentList = commentService.findUserComments(userId,page.getOffset(),page.getLimit());
        List<Map<String,Object>> commentVoList = new ArrayList<>();
        if(commentList != null){
            for (Comment comment : commentList){
                Map<String,Object> map = new HashMap<>();
                map.put("comment",comment);
                DiscussPost post = discussPostService.findDiscussPostById(comment.getEntityId());
                map.put("discussPost",post);
                commentVoList.add(map);
            }
        }
        model.addAttribute("comments",commentVoList);
        return "/site/my-reply";
    }
}
